package com.yonyou.ucf.mdf.app.isvdxq.utils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;

public class SQLFilter implements Filter {

    private String inj_str = "‘|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|; |or|-|+|,";

    protected FilterConfig filterConfig = null;
    /**
     * Should a character encoding specified by the client be ignored?
     */
    protected boolean ignore = true;

    public void init(FilterConfig config) throws ServletException
    {
        this.filterConfig = config;
        this.inj_str = filterConfig.getInitParameter("keywords");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        Iterator values = req.getParameterMap().values().iterator();//获取所有的表单参数

        while (values.hasNext()) {
            String[] value = (String[]) values.next();
            for (int i = 0; i < value.length; i++) {
                if (sql_inj(value[i])) {
                    //TODO这里发现sql注入代码的业务逻辑代码
                    throw new IOException("参数不符合安全标准：" + value[i].toString());
                    //return;
                }
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

    /**
     * 注入安全检测
     * @param str
     * @return
     */
    private boolean sql_inj(String str) {
        String[] inj_stra = inj_str.split("\\|");
        for (int i = 0; i < inj_stra.length; i++) {
            if (str.indexOf(inj_stra[i]) >= 0) {
                return true;
            }
        }

        return false;
    }

    /**
     * 防止sql注入 安全过滤 .*([';]+|(--)+).*
     * @param sql
     * @return
     */
    public static String TransactSQLInjection(String sql) {
        return sql.replaceAll("([';])+|(--)+", " ");
    }
    public static String TransactSQLParamInjection(String filed, String reg) {
        return filed.replaceAll(reg, " ");
    }

    /**
     * 过滤SQL参数
     * @param filed
     * @return
     */
    public static String TransactSQLParamInjection(String filed) {
        String reg = "(--|;|%|or|and)+|(exec|where|insert|select|delete|update|count|chr|mid|master|truncate|char|declare)+";
        reg = "(--|;|%|or|and)+";
        return TransactSQLParamInjection(filed, reg);
    }

}

